const Fs = require('fs');

const deleteFile = async path => {
  let files = [];

  if (Fs.existsSync(path)) {
    if (Fs.statSync(path).isDirectory()) {
      files = Fs.readdirSync(path);
      files.forEach(file => {
        const curPath = `${path}/${file}`;

        if (Fs.statSync(curPath).isDirectory()) {
          deleteFile(curPath);
        } else {
          Fs.unlinkSync(curPath);
        }
      });
      Fs.rmdirSync(path);
    } else {
      Fs.unlinkSync(path);
    }
  }
};

const copyFile = async (from, to) => {
  let files = [];

  if (Fs.existsSync(to)) {
    files = Fs.readdirSync(from);
    files.forEach(file => {
      const targetPath = `${from}/${file}`;
      const toPath = `${to}/${file}`;

      if (Fs.statSync(targetPath).isDirectory()) {
        copyFile(targetPath, toPath);
      } else {
        Fs.copyFileSync(targetPath, toPath);
      }
    });
  } else {
    Fs.mkdirSync(to);
    copyFile(from, to);
  }
};

module.exports = {
  deleteFile,
  copyFile,
};
